package cn.wolfcode.crm.service.impl;

import cn.wolfcode.crm.domain.Client;
import cn.wolfcode.crm.mapper.ClientMapper;
import cn.wolfcode.crm.query.ClientQueryObject;
import cn.wolfcode.crm.service.IClientService;
import cn.wolfcode.crm.util.LogicException;
import cn.wolfcode.crm.util.PageResult;
import cn.wolfcode.crm.util.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.Date;
import java.util.List;

@Service
public class ClientServiceImpl implements IClientService {

    @Autowired
    ClientMapper mapper;

    public int deleteByPrimaryKey(Long id) {
        return mapper.deleteByPrimaryKey(id);
    }

    public int insert(Client record) {
        record.setInputUser(UserContext.getCurrentUser());
        record.setInputTime(new Date());
        return mapper.insert(record);
    }

    public Client selectByPrimaryKey(Long id) {
        return mapper.selectByPrimaryKey(id);
    }

    public List<Client> selectAll() {
        return selectAll();
    }

    public int updateByPrimaryKey(Client record) {
        return mapper.updateByPrimaryKey(record);
    }

    public PageResult list(ClientQueryObject qo) {
        List<String> currentuser_roles = (List<String>) UserContext.getSession().getAttribute("CURRENTUSER_ROLES");
        //如果不是超级管理员也不是销售主管,就把当前用户作为qo负责人高级查询筛选出数据
        if (!(currentuser_roles.contains("ADMIN") || currentuser_roles.contains("销售主管"))){
            qo.setChargeUserName(UserContext.getCurrentUser().getUsername());
        }

        int count = mapper.query4Count(qo);
        if (count > 0) {
            return new PageResult(count, mapper.query4List(qo));
        }
        return new PageResult(count, Collections.EMPTY_LIST);
    }

    //移入资源池
    public void moveIntoClientPool(Long id) {
        mapper.changeStatus(2L,id);
    }

    public void correctClient(Long id) {
        Client client = mapper.selectByPrimaryKey(id);
        if (client.getInChargeUser()==null) {
            throw new LogicException("没有负责人,无法转正");
        }
        client.setForwardTime(new Date());
        mapper.updateForwardTimeById(client);
        mapper.changeStatus(1L,client.getId());
    }

    public void updateInChargeUserByPrimaryKey(Long inChargeUserId,Long id) {
        mapper.updateInChargeUserByPrimaryKey(inChargeUserId,id);
    }

    public void absorb(Long id) {
        mapper.changeStatus(0L,id);
        mapper.updateInChargeUserToNull(id);
    }

    public void changeStatus(long status, Long cId) {
        mapper.changeStatus(status,cId);
    }
}
